package cn.tedu.usersecurity.security;

import cn.tedu.usersecurity.mapper.UserMapper;
import cn.tedu.usersecurity.pojo.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //username代表用户输入的用户名, 通过输入的用户名查询出数据库里面的用户信息
        UserVo user = userMapper.selectByUserName(username);
        //如果user为null代表没有查询到对应的信息 代码用户名不存在
        if (user == null) {
            return null;// 会默认抛出AuthenticationException 用户名找不到的异常
        }

        //准备授权列表
        List<GrantedAuthority> authorities =
                AuthorityUtils.createAuthorityList(user.getIsAdmin()==1?"ADMIN":"USER");
        //如果项目业务中需要得到除了用户名以外的其它用户信息时则需要自定义用户对象
        //此用户对象就是在登录成功时保存到Security上下文里面的用户对象
        AuthenticationUser userDetails = new AuthenticationUser(
                user.getId(),user.getNickname(),
                username,user.getPassword(),
                true,true,
                true,
                true,authorities);
        //如果在认证过程中 密码出错时Security框架会自动抛出异常BadCredentialsException
        return userDetails;
    }
}
